package org.example.mydeom.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.example.mydeom.pojo.entity.User;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;


public class JwtTokenUtil {
    //private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtil.class);
    //private static final String SECRET_KEY="my-very-long-and-secure-secret-key-for-jwt-token-generation-must-be-at-least-32-characters-long";
    public static final Long JWT_TTL = 60 * 60 *1000L;//一个小时
    public static final String HEADER = "token";
    // 缓存密钥以确保一致性
    private static SecretKey cachedSecretKey = null;

    // 生成Token
    public static String generateJwtToken(User user) {
//        List<String> roles = user.getAuthorities().stream()
//                .map(GrantedAuthority::getAuthority)
//                .collect(Collectors.toList());
        return Jwts.builder()
                .setSubject(user.getUsername())
                .claim("userId", user.getId())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + JWT_TTL))
                .signWith(key(), SignatureAlgorithm.HS256)
                .compact();
    }
    // 从Token获取用户名
    public static String getUserNameFromJwtToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(key())
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }

    // 从Token获取角色
    public static Long getUserIdFromJwtToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(key())
                .build()
                .parseClaimsJws(token)
                .getBody();
        return claims.get("userId", Long.class);
    }

    // 验证Token
    public static boolean validateJwtToken(String authToken) {
        try {
            Jwts.parserBuilder().setSigningKey(key()).build().parseClaimsJws(authToken);
            return true;
        } catch (MalformedJwtException e) {
            return false;
        }
    }
    // 生成密钥
    private static Key key() {
        if(cachedSecretKey==null){
            cachedSecretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        }
        return cachedSecretKey;
    }
}
